/**
 * @file icon-button
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {Renderer, render} from './renderer';
import * as cx from 'classnames';
import * as CustomPropTypes from './propTypes';
import * as omit from 'lodash/omit';
import * as pick from 'lodash/pick';
import * as assign from 'object-assign';
import {
  Row,
  Col
} from 'react-bootstrap';
import * as schema from './grid-schema.json';
const ColProps = [
  'lg',
  'lgHidden',
  'lgOffset',
  'lgPull',
  'lgPush',

  'md',
  'mdHidden',
  'mdOffset',
  'mdPull',
  'mdPush',

  'sm',
  'smHidden',
  'smOffset',
  'smPull',
  'smPush',

  'xs',
  'xsHidden',
  'xsOffset',
  'xsPull',
  'xsPush'
];

@Renderer({
  name: 'grid',
  desc: '...',
  test: (path, config) => /(?:^|\/)grid$/.test(path),
  schema
})
export default class GridRenderer extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    columns: PropTypes.array.isRequired
  };

  static defaultProps = {
    className: ''
  };

  renderColumn(column, key, length) {
    const {
      $path,
      $key
    } = this.props;

    const md = Math.floor(12/length);
    let element = null;
    if (Array.isArray(column)) {
      element = column.map((item, key)=>{
        return (
          <Row key={key}>
            <Col md={12}>
              {render(`${$path}/${item.type}`, item, assign(omit(this.props, ['className', 'columns', '$path', 'name']), {
                $index: key
              }))}
            </Col>
          </Row>
        )
      });
    }
    const colProps = pick(Array.isArray(column) ? {
      md
    } : assign({}, {
      md
    }, column), ColProps);

    return (
      <Col
        key={key}
        className={column.columnClassName}
        {...colProps}
      >
        {
          element ? element : render(`${$path}/${column.type}`, column, assign(omit(this.props, ['className', 'columns', '$path', 'name'].concat(ColProps)), {
            $index: key
          }), `${$key}.columns.${key}`)
        }
      </Col>
    );
  }

  render() {
    const {
      className,
      columns,
      dragState
    } = this.props;

    return (
      <Row className={cx(className, {'editor-can-drop': dragState && dragState['columns']})}>
        {columns.map((column, key) => this.renderColumn(
          column, key, columns.length
        ))}
      </Row>
    );
  }
}
